package avicit.bdp.dcs.common.rest;

import avicit.platform6.core.rest.msg.ResponseMsg;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @金航数码科技有限责任公司
 * @作者：developer
 * @邮箱：developer@avic-digital.com
 * @创建时间： 2020-07-23 11:55
 * @类说明：统一异常处理
 * @修改记录：
 */
@ControllerAdvice
@Order(1)
public class GlobalExceptionHandler1 {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler1.class);

    // 数据校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseMsg error(MethodArgumentNotValidException e){
        logger.error(e.getMessage(), e);
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();

        //多个错误，取第一个
        FieldError error = fieldErrors.get(0);
        String msg = error.getDefaultMessage();
        ResponseMsg<Object> objectResponseMsg = new ResponseMsg<>();
        objectResponseMsg.setRetCode(String.valueOf(HttpStatus.SC_BAD_REQUEST));
        objectResponseMsg.setErrorDesc(msg);
        return objectResponseMsg;
    }
}